package com.far.permisions.meta.function;

import com.far.permissions.rule.RuleValueConvertor;
import com.far.permissions.enums.Type;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class FunctionValueConvertor implements RuleValueConvertor {
    private final Map<String, Supplier<?>> supplierMap = new HashMap<>();

    public FunctionValueConvertor(List<FunctionValueHandler<?>> suppliers) {
        if (null != suppliers) {
            for (FunctionValueHandler<?> supplier : suppliers) {
                supplierMap.putIfAbsent(supplier.getCode(), supplier);
            }
        }
    }

    @Override
    public Object convert(Object code) throws Exception {
        return findSupplier((String) code).get();
    }

    @Override
    public String getType() {
        return Type.FUNCTION.name();
    }

    private Supplier<?> findSupplier(String code) {
        return supplierMap.getOrDefault(code, () -> {throw new RuntimeException("no such function supplier");});
    }
}
